package com.example.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.result.PageResult;
import com.example.common.result.Result;
import com.example.common.result.YiFeiException;
import com.example.config.RedisCache;
import com.example.controller.ZnxController;
import com.example.entity.dto.CoptcDto;
import com.example.entity.dto.FileUpload.FileDto;
import com.example.entity.dto.GetCoptcListDto;
import com.example.entity.dto.SaleOrder.BatchUpdateCoptcDto;
import com.example.entity.dto.SaleOrder.BatchUpdateCoptcListDto;
import com.example.entity.dto.SaleOrder.CoptcUpdate;
import com.example.entity.hz.MOCTA;
import com.example.entity.hz.Znx;
import com.example.entity.money.RaxDto;
import com.example.entity.money.RaxVo;
import com.example.entity.vo.Business.BatchUpdateCoptcListVo;
import com.example.entity.vo.Business.CoptcListVo;
import com.example.entity.vo.Business.MoneyAndNum;
import com.example.entity.vo.CoptcGyVo;
import com.example.entity.vo.CoptdFZzVo;
import com.example.entity.yifei.*;
import com.example.entity.ymlConfig.YmlConfig;
import com.example.exception.BaseException;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.service.CmsmqService;
import com.example.service.CoptcService;
import com.example.service.IActFlowCustomService;
import com.example.untils.MoneyUtils;
import com.example.untils.NumUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-02-28
 */
@Service
public class CoptcServiceImpl extends ServiceImpl<CoptcMapper, Coptc> implements CoptcService , IActFlowCustomService {

    @Resource
    private CoptcMapper coptcMapper;

    @Resource
    private CoptdMapper coptdMapper;

    @Resource
    private CopmaMapper copmaMapper;
    @Resource
    private AdmmfMapper admmfMapper;

    @Resource
    private AttachMapper attachMapper;

    @Resource
    private CopmgMapper copmgMapper;

    @Autowired
    private CmsmqService cmsmqService;

    @Autowired
    private CopmdMapper copmdMapper;

    @Resource
    private PurtaMapper purtaMapper;
    @Resource
    private PurtbMapper purtbMapper;

    @Resource
    private PurtcMapper purtcMapper;
    @Resource
    private PurtdMapper purtdMapper;

    @Resource
    private MoctaMapper moctaMapper;

    @Resource
    private RedisCache redisCache;
    @Resource
    private ActFlowCommService actFlowCommService;

    @Resource
    private InvmbMapper invmbMapper;

    @Resource
    private InvmdMapper invmdMapper;

    @Autowired
    private ZnxController znxController;
    @Override
    @DSTransactional
    @Async
    public CompletableFuture<Result> add(CoptcDto coptcDto) {
        synchronized (this) {
            try {
                if (coptcDto == null) {
                    return CompletableFuture.completedFuture(Result.error("参数为空"));
                }
                String creator = coptcDto.getCreator();
                if (StringUtils.isEmpty(creator)) {
                    return CompletableFuture.completedFuture(Result.error("创建人不能为空"));
                }

                QueryWrapper<Admmf> admmfQueryWrapper = new QueryWrapper<>();
                admmfQueryWrapper.eq("MF001", creator);
                Admmf admmf = admmfMapper.selectOne(admmfQueryWrapper);

                if (admmf == null) {
                    return CompletableFuture.completedFuture(Result.error("未找到创建人信息"));
                }

                String usrGroup = admmf.getMf004();
                String time = TimeUtils.getNowTime().substring(0, 8);

                Coptc coptc = coptcDto.getCoptc();
                if (StringUtils.isEmpty(coptc.getTc001())) {
                    redisCache.setCacheObject("insertCoptc", "0");
                    return CompletableFuture.completedFuture(Result.error("单别不能为空"));
                }
                if (coptcDto.getCoptdList().isEmpty()) {
                    redisCache.setCacheObject("insertCoptc", "0");
                    return CompletableFuture.completedFuture(Result.error("单身不能为空"));
                }

                coptc.setCompany(admmf.getCompany());
                coptc.setCreator(creator);
                coptc.setUsr_group(usrGroup);
                coptc.setCreateDate(TimeUtils.getNowTime());
                coptc.setUdf11(coptcDto.getCoptc().getUdf11());
//                coptc.setModiDate(TimeUtils.getNowTime());
                coptc.setFlag(1.0);

                coptc.setREMARK(coptc.getTc015());
                coptc.setTc015("");
                coptc.setTc048("0");
                coptc.setTc027("N");
                coptc.setTc077("********************");

                if (coptc.getTc002().length() > 11) {
                    throw new CustomException("500", "单号不能大于11位");
                }

                Coptc selectOne = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                        .eq(Coptc::getTc001, coptc.getTc001()).eq(Coptc::getTc002, coptc.getTc002()));

                if (selectOne != null) {
                    String id = cmsmqService.getIdByType(coptc.getTc001(), "coptc");
                    coptc.setTc002(id);
                }

                coptcMapper.insert(coptcDto.getCoptc());

                int xh = 1;
                for (Coptd coptd : coptcDto.getCoptdList()) {
                    coptd.setCompany(admmf.getCompany());
                    coptd.setCreator(creator);
                    coptd.setUsrGroup(usrGroup);
                    coptd.setCreateDate(TimeUtils.getNowTime());
//                    coptd.setModifier("");
//                    coptd.setModiDate("");
                    coptd.setFlag(1.0);
                    coptd.setTd001(coptc.getTc001());
                    coptd.setTd002(coptc.getTc002());
                    coptd.setTd003(String.format("%04d", xh));
                    coptd.setUdf04(coptd.getMg005());
                    coptd.setUdf05(coptd.getMg006());
                    coptd.setTd026(1D);   // 折扣率
                    coptd.setTd027("********************");  // 项目编号
                    coptdMapper.insert(coptd);
                    xh++;
                }

                coptcDto.getCoptdList().forEach(arr -> {
                    if (StringUtils.isNotEmpty(coptc.getTc004()) && StringUtils.isNotEmpty(arr.getTd014())) {
                        List<Copmg> copmgs = copmgMapper.selectList(new LambdaQueryWrapper<Copmg>()
                                .eq(Copmg::getMg001, coptc.getTc004()).eq(Copmg::getMg003, arr.getTd014()).eq(Copmg::getMg002,arr.getTd004()));
                        if (copmgs.isEmpty()) {
                            Copmg copmg1 = new Copmg();
                            copmg1.setMg001(coptc.getTc004());
                            copmg1.setCreateDate(TimeUtils.getNowTime());
                            copmg1.setMg002(arr.getTd004());
                            copmg1.setMg003(arr.getTd014());
                            copmg1.setMg005(arr.getMg005());
                            copmg1.setMg006(arr.getMg006());
                            copmgMapper.insert(copmg1);
                        }else {
                            for (Copmg arrs:copmgs) {
                                arrs.setMg005(arr.getMg005());
                                arrs.setMg006(arr.getMg006());
                                copmgMapper.update(arrs,new QueryWrapper<Copmg>()
                                        .eq("MG001", coptc.getTc004()).eq("MG003", arr.getTd014()).eq("MG002",arr.getTd004()));
                            }
                        }
                    }
                });

                if (StringUtils.isNotEmpty(coptc.getTc010()) && StringUtils.isNotEmpty(coptc.getTc004())) {
                    Copma copma = copmaMapper.selectOne(new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()));
                    if (copma != null) {
                        Integer count = copmdMapper.selectCount(new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001, coptc.getTc004())
                                .eq(Copmd::getMd003, coptc.getTc010()));
                        if (count == null || count == 0) {
                            Copmd copmd = new Copmd();
                            copmd.setCompany(YmlConfig.getYFCOMPANY());
                            copmd.setCreator(coptcDto.getCreator());
                            copmd.setCreateDate(TimeUtils.getNowTime());
                            copmd.setFlag(0D);
                            copmd.setMd001(coptc.getTc004());
                            String md002 = copmdMapper.generateMd002(coptc.getTc004());
                            copmd.setMd002(md002);
                            copmd.setMd003(coptc.getTc010());
                            copmd.setMd006(copma.getMa003());
                            copmdMapper.insert(copmd);
                        }
                    }
                    Copma copma1 = this.copmaMapper.selectOne(new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()).eq(Copma::getMa025, coptc.getTc010()));
                    if (copma1==null){
                        copma.setMa025(coptc.getTc010());
                        this.copmaMapper.update(copma,new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()));
                    }
                }

                if (StringUtils.isNotEmpty(coptc.getUdf05()) && StringUtils.isNotEmpty(coptc.getTc004())) {
                    Integer count = copmdMapper.selectCount(new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001,coptc.getTc004()).eq(Copmd::getMd003, coptc.getUdf05()));
                    Copmd copmd = new Copmd();
                    if (count == null || count == 0) {
                        if (coptc.getUdf06()!=null&&!coptc.getTc004().equals("")){
                            Copmd copmd1 = this.copmdMapper.selectOne(new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001, coptc.getTc004()).eq(Copmd::getMd002, coptc.getUdf06()));
                            if (copmd1!=null){
                                copmd.setMd003(coptc.getUdf05());
                                this.copmdMapper.update(copmd, new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001,coptc.getTc004()).eq(Copmd::getMd002, coptc.getUdf06()));
                            }else {
                                copmd.setCompany(YmlConfig.getYFCOMPANY());
                                copmd.setCreator(coptcDto.getCreator());
                                copmd.setCreateDate(TimeUtils.getNowTime());
                                copmd.setFlag(0D);
                                copmd.setMd001(coptc.getTc004());
                                copmd.setMd005(coptc.getTc015());
                                copmd.setMd006(coptc.getUdf03());
                                copmd.setMd007(coptc.getUdf04());
                                copmd.setMd008(coptc.getTc073());
                                copmd.setMd009(coptc.getTc074());
                                copmd.setMd010(coptc.getTc075());
                                copmd.setMd002(coptc.getUdf06());
                                copmd.setMd003(coptc.getUdf05());
                                copmdMapper.insert(copmd);
                            }
                        }else {
                            copmd.setCompany(YmlConfig.getYFCOMPANY());
                            copmd.setCreator(coptcDto.getCreator());
                            copmd.setCreateDate(TimeUtils.getNowTime());
                            copmd.setFlag(0D);
                            copmd.setMd001(coptc.getTc004());
                            copmd.setMd005(coptc.getTc015());
                            copmd.setMd006(coptc.getUdf03());
                            copmd.setMd007(coptc.getUdf04());
                            copmd.setMd008(coptc.getTc073());
                            copmd.setMd009(coptc.getTc074());
                            copmd.setMd010(coptc.getTc075());
                            String md002 = copmdMapper.generateMd002(coptc.getTc004());
                            copmd.setMd002(md002);
                            copmd.setMd003(coptc.getUdf05());
                            copmdMapper.insert(copmd);
                        }
                    }
                    Copma copma1 = this.copmaMapper.selectOne(new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()).eq(Copma::getMa027, coptc.getUdf05()));
                    if (copma1==null){
                        Copma copma = new Copma();
                        copma.setMa027(coptc.getUdf05());
                        this.copmaMapper.update(copma,new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()));
                    }
                }

                if (coptcDto.getFileList() != null && !coptcDto.getFileList().isEmpty()) {
                    int idx = 1;
                    for (FileDto fileDto : coptcDto.getFileList()) {
                        if (StringUtils.isEmpty(fileDto.getDocID())) {
                            continue;
                        }
                        String addDate = TimeUtils.getNowTime().substring(0, 8);
                        Date currentDate = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                        String addTime = sdf.format(currentDate);
                        Attach attach = new Attach("COPI06", coptc.getTc001() + "||" + coptc.getTc002(),
                                null, creator, null, String.format("%03d", idx),
                                null, fileDto.getDocID(), null, addDate, addTime, "TC001||TC002");
                        attachMapper.update(attach, new LambdaQueryWrapper<Attach>().eq(Attach::getDocid, fileDto.getDocID()));
                        idx++;
                    }
                }

                redisCache.setCacheObject("insertCoptc", "0");
                return CompletableFuture.completedFuture(Result.success(coptc.getTc002()));
            } catch (Exception e) {
                redisCache.setCacheObject("insertCoptc", "0");
//                e.printStackTrace();
//                return CompletableFuture.completedFuture(Result.error("新增失败: " + e.getMessage()));
                throw new YiFeiException(500,"销售订单新增失败: " + e.getMessage());
            }
        }
    }


    @Override
    public PageResult selectPage(Integer current, Integer size, GetCoptcListDto getCoptcListDto) {
        PageHelper.startPage(current,size,"COPTC.CREATE_DATE DESC");
        if(getCoptcListDto!=null){
            if (!StringUtils.isEmpty(getCoptcListDto.getOrderId())){
                getCoptcListDto.setSize(getCoptcListDto.getOrderId().length());
            }
        }
        Page<CoptcListVo> page = coptcMapper.selectPageMe(getCoptcListDto);
        String formKey = "coptc";
        PageResult<CoptcListVo> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        List<CoptcListVo> coptcs = page.getResult();
        for (CoptcListVo coptcListVo : coptcs) {
            coptcListVo.setTc015(coptcListVo.getREMARK());
            QueryWrapper<Copma> copmaQueryWrapper = new QueryWrapper<>();
            copmaQueryWrapper.eq("MA001",coptcListVo.getTc004());
            Copma copma = copmaMapper.selectOne(copmaQueryWrapper);
            if (copma!=null&&copma.getMa002()!=null){
                coptcListVo.setUdf08(copma.getMa002());
            }
            String businessKey = formKey + ":" + coptcListVo.getTc001().trim() + ":" + coptcListVo.getTc002();
            String curStatus = actFlowCommService.getCurStatus(businessKey, formKey);
            coptcListVo.setCurStatus(curStatus);
        }
        pageResult.setRecords(coptcs);

        return pageResult;
    }

    @DSTransactional
    @Override
    public Result updateCoptc(CoptcDto coptcDto) {
        if(StringUtils.isEmpty(coptcDto.getCoptc().getTc001())) {
            return Result.error("单别不能为空");
        }
        if(StringUtils.isEmpty(coptcDto.getCoptc().getTc002())) {
            return Result.error("单号不能为空");
        }
        Coptc one = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                .eq(Coptc::getTc001, coptcDto.getCoptc().getTc001()).eq(Coptc::getTc002, coptcDto.getCoptc().getTc002()));
        if(one == null) {
            return Result.error("单据已删除或者不存在");
        }
        if("Y".equals(one.getTc027())) {
            return Result.error("单据已审核,不能修改");
        }else if("V".equals(one.getTc027())) {
            return Result.error("单据已作废,不能修改");
        }
        if("1".equals(one.getTc048())) {
            return Result.error("单据在审核中,不能修改");
        }else if("3".equals(one.getTc048())) {
            return Result.error("单据已审核,不能修改");
        }
        String creator = coptcDto.getCreator();
        QueryWrapper<Admmf> admmfQueryWrapper = new QueryWrapper<>();
        admmfQueryWrapper.eq("MF001",creator);
//        System.out.println(creator);
        Admmf admmf = admmfMapper.selectOne(admmfQueryWrapper);

        String usrGroup = admmf.getMf004();

//        String time = TimeUtils.getNowTime().substring(0, 8);

        Coptc coptc = coptcDto.getCoptc();
        coptc.setCompany(admmf.getCompany());
        coptc.setUsr_group(usrGroup);
        if (coptc.getIdentifier()==1){
            coptc.setModifier(creator);
            coptc.setModiDate(TimeUtils.getNowTime());
            coptc.setUdf12(coptc.getUdf12());
            coptc.setUdf11(coptc.getUdf11());
        }
        coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>()
                .eq(Coptc::getTc001, coptc.getTc001()).eq(Coptc::getTc002, coptc.getTc002()));

        List<Coptd> tableCoptds = coptdMapper.selectList(new LambdaQueryWrapper<Coptd>()
                .eq(Coptd::getTd001, coptc.getTc001()).eq(Coptd::getTd002, coptc.getTc002()));
        Set<String> set = new HashSet<>();
        for(Coptd coptd : tableCoptds) {
            set.add(coptd.getTd003());
        }
        // 拿到用户修改的数据。有序号的说明，不是新增操作
        ArrayList<String> idxs = new ArrayList<>();
        for (Coptd coptd : coptcDto.getCoptdList()) {
            if(StringUtils.isNotEmpty(coptd.getTd003())) {
                idxs.add(coptd.getTd003());
            }
        }
        // 删除数据库中，没有对应的行 （用户删除的行）
        for (Coptd coptd : tableCoptds) {
            boolean flag = false;
            for(String idx : idxs) {
                if(coptd.getTd003().equals(idx)) {
                    flag = true;  break;
                }
            }
            if(!flag) {
                coptdMapper.delete(new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, coptd.getTd001())
                        .eq(Coptd::getTd002, coptd.getTd002()).eq(Coptd::getTd003, coptd.getTd003()));
            }
        }
        // 修改和新增
        for (Coptd coptd : coptcDto.getCoptdList()) {
            if(StringUtils.isEmpty(coptd.getTd003())) {
                coptd.setCreator(creator);
                coptd.setCreateDate(TimeUtils.getNowTime());
                coptd.setUdf11(creator);
            }
            coptd.setCompany(admmf.getCompany());
            coptd.setUsrGroup(usrGroup);
            if (coptd.getIdentifier()==1){
                coptd.setModifier(creator);
                coptd.setModiDate(TimeUtils.getNowTime());
                coptd.setUdf12(coptc.getUdf12());
                coptd.setUdf11(coptc.getUdf11());
            }
            coptd.setFlag(new Double(1));
            coptd.setUdf04(coptd.getMg005());
            coptd.setUdf05(coptd.getMg006());

            if (StringUtils.isNotEmpty(coptc.getTc004()) && StringUtils.isNotEmpty(coptd.getTd014())) {
                List<Copmg> copmgs = copmgMapper.selectList(new LambdaQueryWrapper<Copmg>()
                        .eq(Copmg::getMg001, coptc.getTc004()).eq(Copmg::getMg003, coptd.getTd014()).eq(Copmg::getMg002,coptd.getTd004()));
                if (copmgs.isEmpty()) {
                    Copmg copmg1 = new Copmg();
                    copmg1.setMg001(coptc.getTc004());
                    copmg1.setCreateDate(TimeUtils.getNowTime());
                    copmg1.setMg002(coptd.getTd004());
                    copmg1.setMg003(coptd.getTd014());
                    copmg1.setMg005(coptd.getMg005());
                    copmg1.setMg006(coptd.getMg006());
                    copmgMapper.insert(copmg1);
                }else {
                    for (Copmg arrs:copmgs) {
                        arrs.setMg005(coptd.getMg005());
                        arrs.setMg006(coptd.getMg006());
                        copmgMapper.update(arrs,new QueryWrapper<Copmg>()
                                .eq("MG001", coptc.getTc004()).eq("MG003", coptd.getTd014()).eq("MG002",coptd.getTd004()));
                    }
                }
            }
            if(!set.contains(coptd.getTd003())) {
                coptd.setTd001(coptc.getTc001());
                coptd.setTd002(coptc.getTc002());
                if(StringUtils.isEmpty(coptd.getTd003())) coptd.setTd003(String.format("%04d", coptdMapper.generateTd003(coptc.getTc001(), coptc.getTc002())));
                coptdMapper.insert(coptd);
            }else{
                coptdMapper.update(coptd, new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, coptd.getTd001())
                        .eq(Coptd::getTd002, coptd.getTd002()).eq(Coptd::getTd003, coptd.getTd003()));
            }
        }

        List<Attach> list = attachMapper.selectList(new LambdaQueryWrapper<Attach>().eq(Attach::getParent, "COPI06")
                .eq(Attach::getKeyvalues, coptcDto.getCoptc().getTc001() + "||" + coptcDto.getCoptc().getTc002()));
        int idx = 0;
        System.out.println("+++++++++++-------------++++++++++++");
        System.out.println(list);
        System.out.println(coptcDto.getFileList());
        for(Attach attach : list) {
            boolean f = false;
            idx = Math.max(idx, Integer.parseInt(attach.getSeqno()));
            if(coptcDto.getFileList() != null) {
                for(FileDto fileDto : coptcDto.getFileList()) {
                    if(fileDto.getDocID().trim().equals(attach.getDocid().trim())) {
                        f = true;
                        break;
                    }
                }
                if(f) continue;
            }
            System.out.println("删除：" + attach.getDocid());
            // 找不到的就是删除
            attachMapper.delete(new LambdaQueryWrapper<Attach>().eq(Attach::getDocid, attach.getDocid()));
        }
        idx++;
        if(coptcDto.getFileList() != null) {
            for(FileDto fileDto : coptcDto.getFileList()) {
                Boolean f = false;
                for(Attach attach : list) {
                    if(fileDto.getDocID().trim().equals(attach.getDocid().trim())) {
                        f = true;
                        break;
                    }
                }
                if(f) continue;
                // 找不到的就是新增
                String addDate = TimeUtils.getNowTime().substring(0, 8);
                // 获取当前时间
                Date currentDate = new Date();
                // 格式化日期时间
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                String addTime = sdf.format(currentDate);
                Attach attach = new Attach("COPI06", coptc.getTc001()+"||"+coptc.getTc002(),
                        null, creator, null, String.format("%03d", idx),
                        null, fileDto.getDocID(), null, addDate, addTime, "TC001||TC002");
                attachMapper.update(attach, new LambdaQueryWrapper<Attach>().eq(Attach::getDocid, fileDto.getDocID()));
                idx++;
            }
        }

        if (StringUtils.isNotEmpty(coptc.getTc010()) && StringUtils.isNotEmpty(coptc.getTc004())) {
            Copma copma = copmaMapper.selectOne(new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()));
            if (copma != null) {
                Integer count = copmdMapper.selectCount(new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001, coptc.getTc004())
                        .eq(Copmd::getMd003, coptc.getTc010()));
                if (count == null || count == 0) {
                    Copmd copmd = new Copmd();
                    copmd.setCompany(YmlConfig.getYFCOMPANY());
                    copmd.setCreator(coptcDto.getCreator());
                    copmd.setCreateDate(TimeUtils.getNowTime());
                    copmd.setFlag(0D);
                    copmd.setMd001(coptc.getTc004());
                    String md002 = copmdMapper.generateMd002(coptc.getTc004());
                    copmd.setMd002(md002);
                    copmd.setMd003(coptc.getTc010());
                    copmd.setMd006(copma.getMa003());
                    copmdMapper.insert(copmd);
                }
            }
            Copma copma1 = this.copmaMapper.selectOne(new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()).eq(Copma::getMa025, coptc.getTc010()));
            if (copma1==null){
                copma.setMa025(coptc.getTc010());
                this.copmaMapper.update(copma,new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()));
            }
        }

        if (StringUtils.isNotEmpty(coptc.getUdf05()) && StringUtils.isNotEmpty(coptc.getTc004())) {
            Integer count = copmdMapper.selectCount(new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001,coptc.getTc004()).eq(Copmd::getMd003, coptc.getUdf05()));
            Copmd copmd = new Copmd();
            if (count == null || count == 0) {
                if (coptc.getUdf06()!=null&&!coptc.getTc004().equals("")){
                    Copmd copmd1 = this.copmdMapper.selectOne(new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001, coptc.getTc004()).eq(Copmd::getMd002, coptc.getUdf06()));
                    if (copmd1!=null){
                        copmd.setMd003(coptc.getUdf05());
                        this.copmdMapper.update(copmd, new LambdaQueryWrapper<Copmd>().eq(Copmd::getMd001,coptc.getTc004()).eq(Copmd::getMd002, coptc.getUdf06()));
                    }else {
                        copmd.setCompany(YmlConfig.getYFCOMPANY());
                        copmd.setCreator(coptcDto.getCreator());
                        copmd.setCreateDate(TimeUtils.getNowTime());
                        copmd.setFlag(0D);
                        copmd.setMd001(coptc.getTc004());
                        copmd.setMd005(coptc.getTc015());
                        copmd.setMd006(coptc.getUdf03());
                        copmd.setMd007(coptc.getUdf04());
                        copmd.setMd008(coptc.getTc073());
                        copmd.setMd009(coptc.getTc074());
                        copmd.setMd010(coptc.getTc075());
                        copmd.setMd002(coptc.getUdf06());
                        copmd.setMd003(coptc.getUdf05());
                        copmdMapper.insert(copmd);
                    }
                }else {
                    copmd.setCompany(YmlConfig.getYFCOMPANY());
                    copmd.setCreator(coptcDto.getCreator());
                    copmd.setCreateDate(TimeUtils.getNowTime());
                    copmd.setFlag(0D);
                    copmd.setMd001(coptc.getTc004());
                    copmd.setMd005(coptc.getTc015());
                    copmd.setMd006(coptc.getUdf03());
                    copmd.setMd007(coptc.getUdf04());
                    copmd.setMd008(coptc.getTc073());
                    copmd.setMd009(coptc.getTc074());
                    copmd.setMd010(coptc.getTc075());
                    String md002 = copmdMapper.generateMd002(coptc.getTc004());
                    copmd.setMd002(md002);
                    copmd.setMd003(coptc.getUdf05());
                    copmdMapper.insert(copmd);
                }
            }
            Copma copma1 = this.copmaMapper.selectOne(new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()).eq(Copma::getMa027, coptc.getUdf05()));
            if (copma1==null){
                Copma copma = new Copma();
                copma.setMa027(coptc.getUdf05());
                this.copmaMapper.update(copma,new LambdaQueryWrapper<Copma>().eq(Copma::getMa001, coptc.getTc004()));
            }
        }

        return Result.success("修改成功");
    }

    /**
     * 批量修改列表
     * @param dto
     * @return
     */
    @Override
    public Result<List<BatchUpdateCoptcListVo>> batchUpdateCoptcList(BatchUpdateCoptcListDto dto) {
        List<BatchUpdateCoptcListVo> listVos = coptcMapper.batchUpdateCoptcList(dto);
        return Result.success(listVos);
    }

    @Transactional
    @Override
    public Result batchUpdate(BatchUpdateCoptcDto dto) {
        List<CoptcUpdate> list = dto.getList();

        for(int i = 0; i < list.size(); i++) {
            CoptcUpdate data = list.get(i);
            if(data.getNewNums() == null) {
                data.setNewNums(data.getOriginalOrderNums());
            }
            if(data.getNewPrice() == null) {
                data.setNewPrice(data.getOriginalUnitPrice());
            }
        }

        Map<String, MoneyAndNum> changeValue = new HashMap<>();   // 用来计算单头金额变化的差值
        for(int i = 0; i < list.size(); i++) {
            CoptcUpdate data = list.get(i);
            String saleOrderId = data.getSaleOrderId();  // 单别-单号  注：有些单号可能是有'-'的
            String[] strings = saleOrderId.split("-");
            String TC001 = "";   String TC002 = "";
            if(strings.length == 2) {
                TC001 = strings[0];
                TC002 = strings[1];
            } else if (strings.length == 3) {
                TC001 = strings[0];
                TC002 = strings[1] + "-" + strings[2];
            }
            Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                    .eq(Coptc::getTc001, TC001).eq(Coptc::getTc002, TC002));
            Coptd coptd = coptdMapper.selectOne(new LambdaQueryWrapper<Coptd>()
                    .eq(Coptd::getTd001, TC001).eq(Coptd::getTd002, TC002).eq(Coptd::getTd003, data.getSerialId()));
            String tc016 = coptc.getTc016();  // 税种
//            String tc008 = coptc.getTc008();  // 币种
            Double tc009 = coptc.getTc009();  // 汇率
            Double td037 = coptd.getTd037();  // 税率   要用单身的税率
            RaxDto raxDto = new RaxDto(tc016, new BigDecimal(data.getNewNums()), new BigDecimal(td037),
                    new BigDecimal(data.getNewPrice()), new BigDecimal(tc009));
            RaxVo raxVo = MoneyUtils.getRax(raxDto);
            MoneyAndNum moneyAndNum = changeValue.get(saleOrderId);
            if(moneyAndNum == null) {
                moneyAndNum = new MoneyAndNum(new BigDecimal(0),new BigDecimal(0),new BigDecimal(0),
                        new BigDecimal(0),new BigDecimal(0),new BigDecimal(0),new BigDecimal(0), coptc.getREMARK());
                changeValue.put(saleOrderId, moneyAndNum);
            }
            moneyAndNum.setNums(NumberUtil.sub(moneyAndNum.getNums(), coptd.getTd008()));
            moneyAndNum.setPrice(NumberUtil.sub(moneyAndNum.getPrice(), coptd.getTd012()));
            moneyAndNum.setPriceBeforeTax(NumberUtil.sub(moneyAndNum.getPriceBeforeTax(), coptd.getTd038()));
            moneyAndNum.setTaxPrice(NumberUtil.sub(moneyAndNum.getTaxPrice(), coptd.getTd039()));
            moneyAndNum.setPriceLocal(NumberUtil.sub(moneyAndNum.getPriceLocal(), coptd.getTdi03()));
            moneyAndNum.setPriceBeforeTaxLocal(NumberUtil.sub(moneyAndNum.getPriceBeforeTaxLocal(), coptd.getTdi01()));
            moneyAndNum.setTaxPriceLocal(NumberUtil.sub(moneyAndNum.getTaxPriceLocal(), coptd.getTdi02()));
            moneyAndNum.setTc015(coptc.getREMARK());
            /**
             * TD008 订单数量
             * TD011 单价
             * TD012 金额
             * TD038 税前金额
             * TD039 税额
             * TDI01 本币税前金额
             * TDI02 本币税额
             * TDI03 本币金额
             */
//            System.out.println("+++++++++------------++++++++++++");
//            System.out.println(coptc);
//            System.out.println(coptd);
//            System.out.println(raxDto);
//            System.out.println(raxVo);
            coptd.setTd008(data.getNewNums());
            coptd.setTd011(data.getNewPrice());
            coptd.setTd012(raxVo.getPrice().doubleValue());
            coptd.setTd038(raxVo.getPriceBeforeTax().doubleValue());
            coptd.setTd039(raxVo.getTaxPrice().doubleValue());
            coptd.setTdi01(raxVo.getPriceBeforeTaxLocal().doubleValue());
            coptd.setTdi02(raxVo.getTaxPriceLocal().doubleValue());
            coptd.setTdi03(raxVo.getPriceLocal().doubleValue());
//            coptd.setTd020(data.getDetailRemark());
            // 插入备注
//            if(StringUtils.isNotEmpty(dto.getUpdateRemark())) coptd.setTd020(coptd.getTd020() + "\n" + dto.getUpdateRemark());

            moneyAndNum.setNums(NumberUtil.add(moneyAndNum.getNums(), coptd.getTd008()));
            moneyAndNum.setPrice(NumberUtil.add(moneyAndNum.getPrice(), coptd.getTd012()));
            moneyAndNum.setPriceBeforeTax(NumberUtil.add(moneyAndNum.getPriceBeforeTax(), coptd.getTd038()));
            moneyAndNum.setTaxPrice(NumberUtil.add(moneyAndNum.getTaxPrice(), coptd.getTd039()));
            moneyAndNum.setPriceLocal(NumberUtil.add(moneyAndNum.getPriceLocal(), coptd.getTdi03()));
            moneyAndNum.setPriceBeforeTaxLocal(NumberUtil.add(moneyAndNum.getPriceBeforeTaxLocal(), coptd.getTdi01()));
            moneyAndNum.setTaxPriceLocal(NumberUtil.add(moneyAndNum.getTaxPriceLocal(), coptd.getTdi02()));
            moneyAndNum.setTc015(data.getDetailRemark());
            changeValue.put(saleOrderId, moneyAndNum);
            coptdMapper.update(coptd, new LambdaQueryWrapper<Coptd>()
                    .eq(Coptd::getTd001, TC001).eq(Coptd::getTd002, TC002).eq(Coptd::getTd003, data.getSerialId()));
        }
        for (Map.Entry<String, MoneyAndNum> entry : changeValue.entrySet()) {
//            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            String[] strings = entry.getKey().split("-");
            String TC001 = "";   String TC002 = "";
            if(strings.length == 2) {
                TC001 = strings[0];
                TC002 = strings[1];
            } else if (strings.length == 3) {
                TC001 = strings[0];
                TC002 = strings[1] + "-" + strings[2];
            }
            Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                    .eq(Coptc::getTc001, TC001).eq(Coptc::getTc002, TC002));
            /**
             * TC029 	订单税前金额
             * TC030  	订单税额
             * TC031  	总数量
             * TCI03 	订单本币税前金额
             * TCI04   	订单本币税额
             */
            MoneyAndNum value = entry.getValue();
            coptc.setTc029(NumberUtil.add(coptc.getTc029(), value.getPriceBeforeTax()).doubleValue());
            coptc.setTc030(NumberUtil.add(coptc.getTc030(), value.getTaxPrice()).doubleValue());
            coptc.setTc031(NumberUtil.add(coptc.getTc031(), value.getNums()).doubleValue());
            coptc.setTci03(NumberUtil.add(coptc.getTci03(), value.getPriceBeforeTaxLocal()).doubleValue());
            coptc.setTci04(NumberUtil.add(coptc.getTci04(), value.getTaxPriceLocal()).doubleValue());
            coptc.setREMARK(value.getTc015());
            coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>()
                    .eq(Coptc::getTc001, TC001).eq(Coptc::getTc002, TC002));
        }
        return Result.success("批量修改成功");
    }

    @Override
    public Map<String, Object> setvariables(String id, String userName) {
        Map<String,Object> variables = new HashMap<>();
        variables.put("assignee0",userName);
        variables.put("processInsName","销售订单流程");
        return variables;
    }

    @Override
    public Map<String, Object> setvariables(String id, String userName, Object vo) {
        Map<String,Object> variables = new HashMap<>();
        variables.put("object",vo);
        variables.put("assignee0",userName);
       /* variables.put("assignee1","ERP顾问");
        variables.put("assignee2","ERP顾问");
        //TODO 需要将指定负责人修改为实际的，组别需要根据实际修改
        variables.put("group1","group1");
        variables.put("group2","group2");*/
        variables.put("processInsName","销售订单流程");
        return variables;
    }

    /**
     * 流程实例开始时，需要对采购单的操作，例如将采购单的审核状态置为正在审核
     * @param id id是采购单的唯一标识，单别：单头，中间用冒号隔开
     *           例如：123414124：12414123451
     */
    @Override
    public void startRunTask(String id) {
        System.out.printf("销售单审批流程开始业务操作！！！！！id="+id);
        String[] strings = id.split(":");
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                .eq(Coptc::getTc001, strings[0]).eq(Coptc::getTc002, strings[1]));
        if(coptc == null) {
            throw new CustomException("500", "销售单不存在！");
        }
        // 修改签核状态码，状态到 签核中
        coptc.setTc048("1");
        coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>()
                .eq(Coptc::getTc001, strings[0]).eq(Coptc::getTc002, strings[1]));
    }

    /**
     * 流程实例结束时，需要对采购单的操作，例如将采购单的审核状态置为审核通过或审核未通过
     *
     * @param id
     * @param initiator
     */
    @Transactional
    @Override
    public void endRunTask(String id, Boolean state, String defineId, String initiator) {
        System.out.printf("销售订单审批流程结束业务操作！！！！！id=" + id + "审核状态为：" + state);
        String[] strings = id.split(":");
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                .eq(Coptc::getTc001, strings[0]).eq(Coptc::getTc002, strings[1]));
        if(coptc == null) {
            throw new CustomException("500", "销售订单不存在！");
        }
        if(state) {   // 审批通过
            // 修改签核状态码，状态到 已核准
            coptc.setTc048("3");
            coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>()
                    .eq(Coptc::getTc001, strings[0]).eq(Coptc::getTc002, strings[1]));
            checkCoptc(strings[0], strings[1]);
            List<Znx> znxList = new ArrayList<>();
            switch (defineId){
                case "coptc":
                    Znx znx = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90809").notificationCode(initiator).customField(defineId)
                            .title("通知").build();
                    znxList.add(znx);
                    Znx znx2 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90811").customField(defineId)
                            .title("通知").build();
                    znxList.add(znx2);
                    Znx znx3 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90810").customField(defineId)
                            .title("通知").build();
                    znxList.add(znx3);
                    Znx znx4 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90812").customField(defineId)
                            .title("通知").build();
                    znxList.add(znx4);
                    Znx znx5 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90804").customField(defineId)
                            .title("通知").build();
                    znxList.add(znx5);
                    if (strings[0].equals("ASO")){
                        Znx znx6 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90806").customField(defineId)
                                .title("通知").build();
                        znxList.add(znx6);
                    }
                    break;
                case "coptc2":
                    Znx znx7 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90804").notificationCode(initiator).customField(defineId)
                            .title("通知").build();
                    znxList.add(znx7);
                    Znx znx8 = Znx.builder().code(id).content("有一张新的销售单通过了审核!").departmentCode("90811").customField(defineId)
                            .title("通知").build();
                    znxList.add(znx8);
                    break;
            }
            znxController.insertZnxS(znxList);
        }else{   // 审批未通过
            // 修改签核状态码，状态到 退件
            coptc.setTc048("2");
            coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>()
                    .eq(Coptc::getTc001, strings[0]).eq(Coptc::getTc002, strings[1]));
        }

    }


    @Override
    public Object taskInfo(Map<String, Object> processVariables) {
        Object object = processVariables.get("object");
        return object;
    }

    /**
     * 审核销售单
     * @param TC001 单别
     * @param TC002 单号
     */
    public void checkCoptc(String TC001, String TC002) {
        if(StringUtils.isEmpty(TC001) || StringUtils.isEmpty(TC002)) {
            throw new CustomException("500", "单别或单号为空");
        }
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001)
                .eq(Coptc::getTc002, TC002));
        if(coptc == null) {
            throw new CustomException("500", "订单不存在");
        }
        coptc.setTc027("Y");
        coptcMapper.update(coptc, new LambdaQueryWrapper<Coptc>().eq(Coptc::getTc001, TC001).eq(Coptc::getTc002, TC002));
        Coptd coptd = new Coptd();
        coptd.setTd021("Y");
        coptdMapper.update(coptd, new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, TC001).eq(Coptd::getTd002, TC002));
    }

    @Override
    public Boolean tc30Is0(String tc001, String tc002) {
        Coptc coptc = coptcMapper.selectOne(new LambdaQueryWrapper<Coptc>()
                .eq(Coptc::getTc001, tc001).eq(Coptc::getTc002, tc002));
        if (coptc.getTc048().equals("0")) {
            return true;
        }
        else {
            throw new BaseException(tc001+"-"+tc002+"该销售订单不是未审核销售订单");
        }
    }

    @Override
    public Result<List<CoptcGyVo>> queryCoptcGyVo(String TC001, String TC002) {
        try{
            List<CoptcGyVo> coptcGyVoList = new ArrayList<>();
            List<Coptd> coptdList = coptdMapper.selectList(new LambdaQueryWrapper<Coptd>().eq(Coptd::getTd001, TC001).eq(Coptd::getTd002, TC002));
            // 请购
            if (!coptdList.isEmpty()){
                coptdList.forEach(coptd -> {
                    List<Purtb> purtbList = this.purtbMapper.selectList(new LambdaQueryWrapper<Purtb>().eq(Purtb::getTb029, coptd.getTd001()).eq(Purtb::getTb030, coptd.getTd002()).eq(Purtb::getTb031,coptd.getTd003()).orderByAsc(Purtb::getTb003));
                    if (!purtbList.isEmpty()){
                        purtbList.forEach(arr -> {
                            CoptcGyVo coptcGyVo = new CoptcGyVo();
                            coptcGyVo.setDb(arr.getTb001());
                            coptcGyVo.setDh(arr.getTb002());
                            coptcGyVo.setLx("请购单");
                            coptcGyVo.setMx(coptd.getTd003());
                            coptcGyVo.setStatus(arr.getTb025());
                            Purta purta = this.purtaMapper.selectOne(new LambdaQueryWrapper<Purta>().eq(Purta::getTa001, arr.getTb001()).eq(Purta::getTa002, arr.getTb002()));
                            if (purta!=null){
                                coptcGyVo.setDatetime(purta.getTa003());
                            }
                            coptcGyVo.setGymx(arr.getTb003());
                            coptcGyVo.setCode(arr.getTb004());
                            coptcGyVo.setName(arr.getTb005());
                            coptcGyVo.setGg(arr.getTb006());
                            coptcGyVo.setUnit(arr.getTb007());
                            coptcGyVo.setNum(arr.getTb009());
                            Invmb invmb = this.invmbMapper.selectOne(new LambdaQueryWrapper<Invmb>().eq(Invmb::getMb001, arr.getTb004()));
                            if (invmb!=null){
                                if (invmb.getMb039()!=0&&invmb.getMb040()!=0){
                                    if (arr.getTb015().equals(arr.getTb007())&&arr.getTb043().equals(arr.getTb007())){
                                        Double test = NumUtils.test(arr.getTb009(),1.0, invmb.getMb039(), invmb.getMb040());
                                        double number = test/1.0;
                                        coptcGyVo.setJbnum(test(number));
                                    }else {
                                        // 采购单位换算
                                        Invmd invmd = this.invmdMapper.selectOne(new LambdaQueryWrapper<Invmd>().eq(Invmd::getMD001, arr.getTb004()).eq(Invmd::getMD002, arr.getTb015()));
                                        if (invmd!=null){
                                            Double test = NumUtils.test(arr.getTb009(), invmd.getMD004().doubleValue(), invmb.getMb039(),invmb.getMb040());
                                            double number = test/invmd.getMD004().doubleValue();
                                            coptcGyVo.setJbnum(test(number));
                                        }
                                    }
                                }else {
                                    coptcGyVo.setJbnum(arr.getTb009());
                                }
                            }else {
                                coptcGyVo.setJbnum(arr.getTb009());
                            }
                            coptcGyVo.setBz(arr.getTb024());
                            coptcGyVoList.add(coptcGyVo);
                        });
                        purtbList.forEach(arr -> {
                            // 采购
                            List<Purtd> purtdList = this.purtdMapper.selectList(new LambdaQueryWrapper<Purtd>().eq(Purtd::getTd026, arr.getTb001()).eq(Purtd::getTd027, arr.getTb002()).eq(Purtd::getTd028, arr.getTb003()).orderByAsc(Purtd::getTd003));
                            if (!purtdList.isEmpty()){
                                purtdList.forEach(arrs -> {
                                    CoptcGyVo coptcGyVo2 = new CoptcGyVo();
                                    coptcGyVo2.setDb(arrs.getTd001());
                                    coptcGyVo2.setDh(arrs.getTd002());
                                    coptcGyVo2.setLx("采购单");
                                    coptcGyVo2.setMx(coptd.getTd003());
                                    coptcGyVo2.setStatus(arrs.getTd018());
                                    Purtc purtc = this.purtcMapper.selectOne(new LambdaQueryWrapper<Purtc>().eq(Purtc::getTc001, arrs.getTd001()).eq(Purtc::getTc002, arrs.getTd002()));
                                    if (purtc!=null){
                                        coptcGyVo2.setDatetime(purtc.getTc003());
                                    }
                                    coptcGyVo2.setGymx(arrs.getTd003());
                                    coptcGyVo2.setCode(arrs.getTd004());
                                    coptcGyVo2.setName(arrs.getTd005());
                                    coptcGyVo2.setGg(arrs.getTd006());
                                    coptcGyVo2.setUnit(arrs.getTd009());
                                    coptcGyVo2.setNum(arrs.getTd008());
                                    coptcGyVo2.setJbnum(arrs.getTd008());
                                    coptcGyVo2.setBz(arrs.getTd014());
                                    coptcGyVo2.setDaohuostatus(arrs.getTd016());

                                    coptcGyVoList.add(coptcGyVo2);
                                });
                            }
                        });
                    }
                    List<MOCTA> moctaList = this.moctaMapper.selectList(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA026, coptd.getTd001()).eq(MOCTA::getTA027, coptd.getTd002()).eq(MOCTA::getTA028, coptd.getTd003()).orderByAsc(MOCTA::getTA002));
                    if (!moctaList.isEmpty()){
                        moctaList.forEach(arrs -> {
                            CoptcGyVo coptcGyVo2 = new CoptcGyVo();
                            coptcGyVo2.setDb(arrs.getTA001());
                            coptcGyVo2.setDh(arrs.getTA002());
                            coptcGyVo2.setLx("工单");
                            coptcGyVo2.setMx(coptd.getTd003());
                            coptcGyVo2.setStatus(arrs.getTA013());
                            coptcGyVo2.setDatetime(arrs.getTA003());
                            coptcGyVo2.setGymx("0001");
                            coptcGyVo2.setCode(arrs.getTA006());
                            coptcGyVo2.setName(arrs.getTA034());
                            coptcGyVo2.setGg(arrs.getTA035());
                            coptcGyVo2.setUnit(arrs.getTA007());
                            coptcGyVo2.setNum(arrs.getTA015().doubleValue());
                            coptcGyVo2.setJbnum(arrs.getTA015().doubleValue());
                            coptcGyVo2.setBz(arrs.getTA029());

                            coptcGyVoList.add(coptcGyVo2);
                        });
                    }
                });
            }
            return Result.success(coptcGyVoList);
        }catch (Exception e){
            throw new YiFeiException(500,"销售订单关联查询发生异常"+e.getMessage());
        }
    }

    private double test(double number) {
        double aa;
        if (number == Math.floor(number)) {
            // 变量为整数
            aa = number;
        } else {
            // 变量不是整数
            aa = (double) Math.ceil(number);
        }
      return aa;
    }

    @Override
    public Result queryCoptdFZz(CoptdFZzVo coptdFZzVo) {
        try{
            Map<String,Object> map = new HashMap<>();
            PageHelper.startPage(coptdFZzVo.getCurrent(),coptdFZzVo.getSize());
            List<CoptdFZzVo> coptdFZzVoList = this.coptdMapper.queryIpageFzz(coptdFZzVo);
            PageInfo<CoptdFZzVo> coptdFZzVoPageInfo = new PageInfo<>(coptdFZzVoList);
            if (!coptdFZzVoPageInfo.getList().isEmpty()){
                coptdFZzVoPageInfo.getList().forEach(arr -> {
                    if(arr.getNum()!=null){
                        arr.setNum(arr.getNum());
                    }else {
                        arr.setNum(arr.getTd008());
                    }
                    if(arr.getJhdate()!=null){
                        arr.setJhdate(arr.getJhdate());
                    }else {
                        arr.setJhdate(arr.getTd013());
                    }
                    if(arr.getYsdz()!=null){
                        arr.setYsdz(arr.getYsdz());
                    }else {
                        arr.setYsdz(arr.getTc010());
                    }
                });
            }
            map.put("pages", coptdFZzVoPageInfo.getPages());
            map.put("total", coptdFZzVoPageInfo.getTotal());
            map.put("list", coptdFZzVoPageInfo.getList());
            return Result.success(map);
        }catch (Exception e){
            throw new YiFeiException(500,"查询销售订单风嘴组分页发生异常"+e.getMessage());
        }
    }
}
